package com.globaldom.web.Civics;

import java.util.HashMap;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.globaldom.model.CivResource;
import com.globaldom.utils.Constants;
import com.globaldom.utils.PMF;
import com.globaldom.utils.SessionManager;

@Controller
@RequestMapping(value = "/addcivilian")
public class CivilianAddController {
	public CivilianAddController() {
	}

	/*
	 * Get number of civilians/resources param: type of civilian Add civilian
	 * param:type of civilian
	 * 
	 * FIXME Need to update the existing record. Need for consistency check Need
	 * for error/exception checking
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> addCivilian(@RequestParam int civType, @RequestParam int civNum, HttpSession session,
			HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		// FIXME. Need to make this as reasearchable!
		if (civNum < 0 || civNum > 300) {
			map.put(Constants.STATUS, "+OK");
			map.put(Constants.CODE, civNum + "");
			return map;
		}
		String personID = SessionManager.getID(request, session);
		if(null==personID) 
			{
			map = new HashMap<String, String>();
			map.put(Constants.STATUS, "-ER");
			map.put(Constants.CODE, "401");
			return map;
			}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			CivResource cv = pm.getObjectById(CivResource.class, personID +"/" + civType);
			
			if (cv.getCivDeployed() == civNum) {
				map.put(Constants.STATUS, "-OK");
				map.put(Constants.CODE, "304");
				return map;
			}
			cv.setCivDeployed(civNum);
			map.put(Constants.STATUS, "+OK");
			map.put(Constants.CODE, "" + cv.getCivDeployed());
		} finally {
			pm.close();
		}

		return map;
	}

}
